var gulp = require('gulp');
var del = require('del');
var merge = require('merge-stream');
var smushit = require('gulp-smushit');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var inject = require('gulp-inject');
var browserSync = require('browser-sync').create();

var jsonParse = require('./tools/jsonPlugin');
var taskPath = require('./path');

module.exports = {
    // 清理项目文件
    clean: function (callback) {
        return del([taskPath.DIR_BUILD], callback);
    },

    // 开启服务器
    openServer: function () {
        browserSync.init({
            server: {
                baseDir: "./dist/"
            },
            port: 8181
        });
    },

    // 复制WxConfig资源
    copyResConfig: function (callback) {
        return gulp.src(taskPath.RES_CONFIG.src)
            .pipe(gulp.dest(taskPath.DIR_BUILD));
    },

    // 复制其他静态资源
    copyResOther: function (callback) {
        return gulp.src(taskPath.RES_OTHER)
            .pipe(gulp.dest(taskPath.DIR_BUILD));
    },

    // 从发布目录下面复制版本资源
    copyResWithVerAndDir: function (version, folder) {
        console.log(taskPath.DIR_WEB + version + '/' + folder + '/**/*')
        return gulp.src([taskPath.DIR_WEB + version + '/' + folder + '/**/*'])
            .pipe(gulp.dest(taskPath.DIR_BUILD + '/' + folder + '/'));
    },

    // release版本目录下复制引擎文件
    copyResEgretWithVer: function (version) {
        var srcList = taskPath.RES_EGRET.src.map(function (url) {
            return taskPath.DIR_WEB + version + '/' + url
        });
        return gulp.src(srcList)
            .pipe(concat(taskPath.RES_EGRET.common))
            .pipe(uglify())
            .pipe(gulp.dest(taskPath.DIR_BUILD + '/libs'));
    },

    // release版本目录下复制需要main.min.js和index.html
    copyResVersion: function (version) {
        var folders = [{
            from: taskPath.DIR_WEB + version + '/index.html',
            dist: taskPath.DIR_BUILD
        }, {
            from: taskPath.DIR_WEB + version + '/main.min.js',
            dist: taskPath.DIR_BUILD + '/libs'
        }];

        var tasks = folders.map(function (folder) {
            return gulp.src(folder.from)
                .pipe(gulp.dest(folder.dist));
        });

        return merge(tasks);
    },
    // 压缩folder目录下面的所有json资源
    minifyResourceJson: function (folder) {
        var path = taskPath.DIR_BUILD + '/' + folder;
        return gulp.src(path + '/**/*.json')
            .pipe(jsonParse())
            .pipe(gulp.dest(path))
            .on("finish", function () {
                console.log("处理JSON完成")
            });
    },

    // 压缩图片资源
    minifyResourceImg: function (folder) {
        var path = taskPath.DIR_BUILD + '/' + folder;
        return gulp.src(path + '/**/*.{png,jpg,gif,ico}')
            .pipe(smushit({
                verbose: true
            }))
            .pipe(gulp.dest(path))
            .on("finish", function () {
                console.log("处理Image完成")
            });
    },

    injectHtmlWithTag: function (pagesName = 'index', md5Url, startTag, endTag, opts) {
        opts = opts || {};

        var path;
        if (Object.prototype.toString.call(pagesName) === '[object Array]') {
            path = pagesName.map(function (item, index) {
                return `${taskPath.DIR_BUILD}/${item}.html`;
            });
        } else {
            path = `${taskPath.DIR_BUILD}/${pagesName}.html`;
        }

        console.log(path);

        var taskInject = gulp.src(path)
            .pipe(inject(gulp.src(path), {
                starttag: startTag,
                endtag: endTag,
                relative: true,
                transform: function (filePath, file) {
                    var attrStr = '';
                    if (opts.style == 2) {
                        return `<link rel="stylesheet" type="text/css" href="${md5Url}"/>`;
                    } else {
                        for (var key in opts) {
                            if (key != 'style' && opts.hasOwnProperty(key))
                                attrStr += ` ${key}="${opts[key]}"`
                        }
                        return `<script ${attrStr == '' ? '' : attrStr } src="${md5Url}"></script>`;
                    }
                }
            }))
            .pipe(gulp.dest(taskPath.DIR_BUILD));
        return taskInject;
    }
};
